<template>
  <!--  盘点-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" label-width="auto">
        <el-form-item label="仓库">
          <el-tree-select v-model="searchParam.warehouseId" :data="wareList" check-strictly clearable filterable
                          :render-after-expand="false" :props="{
              children: 'sonList',
              label: 'warehouseName',
              value: 'id'
            }" style="width: 200px" @change="wareChange"/>
        </el-form-item>
        <el-form-item label="库位">
          <el-select v-model="searchParam.storageId" placeholder="请选择" clearable filterable style="width: 200px">
            <el-option v-for="item in storageList" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点单号">
          <el-input v-model="searchParam.no" placeholder="请输入盘点单号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="创建时间" prop="times" style="width: 450px">
          <el-date-picker v-model="searchParam.createTimeList" type="datetimerange" start-placeholder="开始时间"
                          end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>列表信息</div>
        </div>
        <div class="pageTableButView">
          <el-button type="primary" icon="Plus" @click="addStock">新建</el-button>
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     :disabled="multipleSelection.length == 0"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="calc(100vh - 320px)" row-key="id" :stripe="false" border
                @selection-change="handleSelectionChange" header-cell-class-name="witheTableHeader"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="盘点单号" prop="no" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="物料名称" prop="beforeMaterialName" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="批次号" prop="beforeBatchNo" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="库位名称" prop="storageName" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="盘点前数量" prop="beforeCount" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="盘点后数量" prop="laterCount" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="创建人" prop="createUserName" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="创建时间" prop="createTime" min-width="200" show-overflow-tooltip align="center"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
                       :current-page="currentPage" @size-change="handleSizeChange"
                       :page-sizes="[10, 20, 50, 100, 200, 500]"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle + '盘点'" width="1000px">
      <el-form :model="formData" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-tree-select v-model="formData.warehouseId" :data="wareList" :disabled="popType == 1" check-strictly
                              :render-after-expand="false" :props="{
                  children: 'sonList',
                  label: 'warehouseName',
                  value: 'id',
                }" style="width: 250px" @change="wareChange2"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位" prop="storageId">
              <el-select v-model="formData.storageId" :disabled="popType == 1" placeholder="请选择"
                         style="width: 250px">
                <el-option v-for="item in storageList2" :key="item.id" :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                  v-model="formData.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 点击入库弹窗 -->
    <el-dialog title="生产退库" width="500px" v-model="rollbackShow">
      <el-form label-width="auto">
        <el-form-item label="目标库位">
          <el-tree-select style="width: 400px" v-model="formRollback.warehouseId" :data="wareList" check-strictly
                          clearable
                          filterable :render-after-expand="false" :props="{
              children: 'sonList',
              label: 'warehouseName',
              value: 'id',
            }" @change="wareChange2"/>
        </el-form-item>
        <el-form-item label="目标储位">
          <el-select v-model="formRollback.storageId2" placeholder="请选择" clearable filterable style="width: 400px">
            <el-option v-for="item in storageList2" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="退库备注">
          <el-input v-model="formRollback.remark" style="width: 400px" :rows="2" type="textarea"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rollbackShow = false">取 消</el-button>
          <el-button type="primary" @click="rollbackShowOK">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {computed, getCurrentInstance, onMounted, ref} from 'vue';
import type {FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, DocumentDelete, Plus, Refresh, Search, Switch} from '@element-plus/icons-vue';
import axios from 'axios';

const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const formRollback = ref({});
const rollbackShow = ref(false);
const materialStatusType = ref([
  {code: 0, description: '不可用'},
  {code: 1, description: '可用'},
  {code: 4, description: '不合格'},
  {code: 5, description: '报废'}
]);
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};


const formData = ref({
  planNo: '',
  name: '',
  planBeginTime: null,
  planEndTime: null,
  actualBeginTime: null,
  actualEndTime: null,
  organizationId: '',
  status: '0',
  type: '0'
});

const crudTitle = computed(() => {
  if (popType.value === 1) {
    return '查看';
  } else {
    return isEdit.value ? '编辑' : '新建';
  }
});

const showDetail = ref(false);


// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  currentPage.value = 1;
  // currentPage.value = 1
  getList();
};

const procedureOrderList = ref({});
const wareList = ref({});
const storageList = ref({});
const storageList2 = ref([]);
const materiaList = ref({});
const showOutIn = ref(false);
const outInForm = ref({
  materialName: '',
  materialCount: '',
  warehouseId: '',
  storageId: '',
  batchNo: ''
});
const outInFormRef = ref(null);
const outInRules = reactive<FormRules<outInForm>>({
  materialCount: [
    {required: true, message: '请输入数量', trigger: 'blur'}
  ],
  warehouseId: [
    {required: true, message: '请选择入库仓库', trigger: 'change'}
  ],
  storageId: [
    {required: true, message: '请选择入库库位', trigger: 'change'}
  ],
  batchNo: [
    {required: true, message: '请选择批次号', trigger: 'blur'}
  ]
});

const materialStatusChange = (row, type) => {
  // 根据type获取描述
  const statusDescription = materialStatusType.value.find(item => item.code === type).description;

  // 显示确认对话框
  ElMessageBox.confirm(`是否改变物料状态为${statusDescription}?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户确认后的操作
    axiosInstance.post('/api/warehouseStorageMaterial/updateMaterialStatus', {
      id: row.id,
      materialStatus: type
    })
        .then((res) => {
          if (res.code !== 200) {
            ElMessage.warning(res.message);
            return false;
          }
          ElMessage.success('操作成功');
          getList();
        });
  });
};


const outFatherInfo = ref({});
const showRollback = (row) => {
  formRollback.value = {
    ...row,
    storageId: '',
    remark: ''

  };
  storageList2.value = [];
  rollbackShow.value = true;
};
const rollbackShowOK = () => {
  axiosInstance.post('/api/warehouseStorageMaterial/productionRetreatWarehouse', {
    storageId: formRollback.value.storageId2,
    id: formRollback.value.id,
    remark: formRollback.value.remark
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        ElMessage.success('操作成功');
        rollbackShow.value = false;
        getList();
      });
};
const doOutIn = (row) => {
  outInForm.value = JSON.parse(JSON.stringify(row));
  // this.materialCount = JSON.parse(JSON.stringify(param.materialCount))
  // 循环列表 找出子单据的父级
  // 提交时只提交父级和该条子单据

  for (const item of paginatedData.value) {
    if (item.children && item.children.length > 0) {
      for (const items of item.children) {
        if (items.id === row.id) {
          outFatherInfo.value = item;
          outInForm.value.targetWarehouseId = item.targetWarehouseId;
          outInForm.value.storageId = item.storageId;
          wareChange(item.targetWarehouseId);
        }
      }
    }
  }
  showOutIn.value = true;
};

const handleConfigDelete = (e) => {
  formData.value.details.splice(e, 1);
};

const materialStatusList = ref([
  {
    value: 0,
    label: '未加工'
  },
  {
    value: 1,
    label: '已加工'
  }
]);

const wareChange = (e, type) => {
  if (!type) {
    formData.value.storageId = null;
  }
  // storageList.value = {}
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList.value = res.data.records;
      });
};
const wareChange2 = (e, type) => {

  // storageList.value = {}
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList2.value = res.data.records;
      });
};
const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const {proxy}: any = getCurrentInstance();

const qrCodeForm = ref({});
const qrCodeShow = ref(false);
const qrCodeSplit = () => {
  qrCodeForm.value = {
    id: multipleSelection.value[0].id
  };
  qrCodeShow.value = true;
};

const qrCodePush = () => {
  // element 二次确认
  ElMessageBox.confirm('确定合并二维码？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id);
    axiosInstance.post('/api/warehouseStorageMaterial/qrCodeMerge', ids)
        .then((res) => {
          if (res.code !== 200) {
            ElMessage.warning(res.message);
            return false;
          }
          ElMessage.success('操作成功');
          getList();
        });
  });
};

const doQrCodeSplit = () => {
  console.log(qrCodeForm.value);

  if (!qrCodeForm.value.count) {
    ElMessage.error('请输入拆分数量');
    return false;
  }

  axiosInstance.post('/api/warehouseStorageMaterial/qrCodeSplit', qrCodeForm.value)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        ElMessage.success('操作成功');
        qrCodeShow.value = false;
        getList();
      });
};
// 箱码
const printBoxClick = () => {
  const templateName = 'test_print1/warehouseStorageMaterial.cpt';
  proxy.$printClick(templateName, multipleSelection.value);
};
// 打印
const printClick = () => {
  // for (const item of multipleSelection.value) {
  // 	item.id = item.batchNo;
  // }
  const templateName = 'test_print1/warehouseSupplementTemplate.cpt';
  proxy.$printClick(templateName, multipleSelection.value);
};


const getOption = () => {
  axiosInstance
      .post('/api/basedataMaterial/getAll', {}).then(res => {
    if (res.code == 200) {
      const list = res.data;
      const loop = [];
      for (const item of list) {
        loop.push(
            {
              value: item.id,
              label: item.materialName
            }
        );
      }
      materiaList.value = loop;
    }
  });
  axiosInstance.post('/api/planProcedureOrder/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = res.data;
        const loop = [];
        for (const item of list) {
          loop.push(
              {
                value: item.id,
                label: item.materialName
              }
          );
        }
        procedureOrderList.value = list;
      });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });

  // axiosInstance.post('/api/qualitySchemeTask/getPage', {})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false
  //       }
  //       storageList.value = res.data
  //     })
};


const getTypeName = (type: string) => {
  const name = typeList.value.find((item: any) => item.value === type);
  return name ? name.label : '';
};

const typeList = ref([
  {label: '未完成', value: '0'},
  {label: '已完成', value: '1'}
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

const transferType = ref({status: 2});

// 新建记录
const addStock = () => {
  isEdit.value = false;
  formData.value = {};
  showCrud.value = true;
};
import moment from 'moment';

const downLoading = ref(false);
const handleExport = () => {

  downLoading.value = true;
  axios.post('/api/stocktakePlanDetail/excel', {
    ids: multipleSelection.value.map(item => item.id)
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', multipleSelection.value[0].no + '盘点记录' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


const popType = ref(0);//0 编辑 1 只读


const statusList = ref([{
  label: '不可用',
  value: 0
}, {
  label: '可用',
  value: 1
}, {
  label: '运输中',
  value: 2
}, {
  label: '生产锁定',
  value: 3
}, {
  label: '不合格',
  value: 4
}, {
  label: '报废',
  value: 5
}]);

const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '不可用';
    case 1:
      return '可用';
    case 2:
      return '运输中';
    case 3:
      return '生产锁定';
    case 4:
      return '不合格';
    case 5:
      return '报废';
  }
};

const formatProcessingAttributes = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '未加工';
    case 1:
      return '已加工';

  }
};

const rejectShow = ref({});

// 编辑记录
const
    handleEdit = (row: any, type) => {
      // console.log(row,'czqRow')
      ElMessageBox.prompt('请输入驳回原因', '驳回', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
          .then(({value}) => {
            row.remark = value;
            const param = {
              id: row.materialTransferOrderId,
              code: row.orderNo,
              details: [row],
              tasks: [row]
            };
            axiosInstance.post('/api/warehouseMaterialTransferOrder/reject', param).then((res) => {
              if (res.code === 200) {
                getList();
                ElMessage.success('驳回成功');

              } else {
                ElMessage.warning(res.message);
              }
            });
          });
      // isEdit.value = true;
      // formData.value = {...row};
      // axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
      //   if (res.code !== 200) {
      //     ElMessage.warning(res.message);
      //     return false;
      //   }
      //   formData.value.details = res.data.children
      //   if (type) {
      //     // 查看详情
      //     popType.value = type
      //     showDetail.value = true
      //   } else {
      //     // 编辑
      //     popType.value = 0
      //     showCrud.value = true;
      //   }
      //   wareChange(e.targetWarehouseId)
      // })
    };


// 保存记录
const handleSave = async () => {
  if (!formData.value.warehouseId) {
    ElMessage.warning('请选择仓库');
    return false;
  }
  // if (!formData.value.storageId) {
  // 	ElMessage.warning('请选择库位');
  // 	return false;
  // }
  axiosInstance.post('/api/stocktakePlan/save', {...formData.value})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        showCrud.value = false;
        getList();
      });
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    rowChildren(row);
  } else {
    // getList();
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const listGroup = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return {...item, children: res.data.children};
      }
      return item;
    });
    paginatedData.value = listGroup;
  });
  // axiosInstance.post('/api/报工总数打印/getAll', {planId: row.id})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false
  //       }
  //
  //       .value = res.data
  //     });

  // ProductionPlanDetailApi().then((res) => {
  //   if (res.code !== 200) {
  //     ElMessage.warning(res.message);
  //     return false;
  //   }
  //   const listGroup = paginatedData.value.map((item) => {
  //     if (item.id === row.id) {
  //       return {...item, children: res.data.records};
  //     }
  //     return item;
  //   });
  //   paginatedData.value = listGroup;
  // });
};

const pageTotal = ref(0);

const loadCache = () => {
  const cachedWarehouseId = localStorage.getItem('inventoryDetailWarehouseId');
  const cachedStorageId = localStorage.getItem('inventoryDetailStorageId');
  if (cachedWarehouseId) {
    searchParam.value.warehouseId = cachedWarehouseId;
    wareChange(cachedWarehouseId);
  }
  if (cachedStorageId) {
    searchParam.value.storageId = cachedStorageId;
  }
};

// 获取列表
const getList = async () => {
  // if (searchParam.value.warehouseId) {
  // 	localStorage.setItem('inventoryDetailWarehouseId', searchParam.value.warehouseId);
  // }
  // if (searchParam.value.storageId) {
  // 	localStorage.setItem('inventoryDetailStorageId', searchParam.value.storageId);
  // }
  axiosInstance.post('/api/stocktakePlanDetail/getPage', {
    ...searchParam.value,
    current: currentPage.value,
    pageSize: pageSize.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records.map((item) => ({
          ...item,
          children: [],
          layer: 1,
          _loading: false
        }));
        pageTotal.value = res.data.total;
      });
};

onMounted(() => {
  // loadCache();
  getList();
  getOption();
});
</script>
<style scoped lang="scss"></style>
